package com.beyondsoft.mcms.domain;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.annotations.Type;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

import com.beyondsoft.mcms.common.CommonUtils;
import com.beyondsoft.mcms.reference.AuthRole;

@RooJavaBean
@RooToString
@RooJpaActiveRecord(finders = { "findUsersesByUsernameEquals", "findUsersesByUsernameLikeAndAuthority" })
public class Users {

    /**
     */
    @NotNull
    @Size(min = 1)
    @Column(unique = true)
    @Pattern(regexp = "^[A-Za-z_0-9]{1,15}$")
    private String username;

    /**
     */
    @NotNull
    private String password;

    /**
     */
    @NotNull
    @Type(type = "java.lang.Boolean")
    private Boolean enabled = true;

    /**
     */
    private String realName;

    /**
     */
    @NotNull
    @Enumerated(EnumType.STRING)
    private AuthRole authority;

    /**
     */
    private String createdBy;

    /**
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "MM")
    private Date createDate;

    /**
     */
    private String updatedBy;

    /**
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "MM")
    private Date updateDate;

    public static TypedQuery<Users> findUsersesByUsernameLikeAndAuthority(String username, AuthRole authority) {
        
    	if (username == null || username.length() == 0) username = "*";
    	username = username.replace('*', '%');
		if (username.charAt(0) != '%') {
			username = "%" + username;
		}
		if (username.charAt(username.length() - 1) != '%') {
			username = username + "%";
		}
		
		StringBuffer sql = new StringBuffer("SELECT o FROM Users AS o WHERE o.authority != 'SUPERVISOR' ");
        if (AuthRole.ADMIN.equals(CommonUtils.getCurrentRole())) {
            sql.append("  and  o.authority != 'ADMIN' ");
        }
        
        sql.append(" and LOWER(o.username) LIKE LOWER(:username) ");
        
        EntityManager em = Users.entityManager();
        if (authority!= null && (!authority.equals(AuthRole.SUPERVISOR)) ){
            sql.append("  AND  o.authority = :authority" );
        }
        
		TypedQuery<Users> q = em.createQuery(sql.toString(), Users.class);
        q.setParameter("username", username);

        if (authority!= null && (!authority.equals(AuthRole.SUPERVISOR)) ){
        	q.setParameter("authority", authority);
        }
        
        return q;
    }
    
    
}
